package com.ovopark.firecar.presenter

import android.content.Context
import com.caoustc.okhttplib.okhttp.OkHttpRequestParams
import com.caoustc.okhttplib.okhttp.callback.StringHttpRequestCallback
import com.ovopark.firecar.bean.UserBean
import com.ovopark.firecar.manager.DataManager
import com.ovopark.firecar.manager.UserCacheManager
import com.ovopark.firecar.okhttp.OkHttpRequest
import com.ovopark.firecar.view.ILoginView
import org.json.JSONObject

class LoginPresenter(var mcontext : Context,var view : ILoginView) {

    fun Login(username : String,passowrd : String,type : String){
        var param = OkHttpRequestParams()
        param.addBodyParameter("login",username)
        param.addBodyParameter("password",passowrd)
        param.addBodyParameter("type",type)
        OkHttpRequest.post(DataManager.getInstance().getBaseUrl()+DataManager.LOGIN,param,object : StringHttpRequestCallback(){
            override fun onSuccess(data: String?) {
                super.onSuccess(data)
                var code : Int = JSONObject(data).optInt("errcode")
                var errorMessage = JSONObject(data).optString("errmsg")
                var message = JSONObject(data).optString("message")
                if (code==0){
                    var result = JSONObject(data).optString("data")
                    var token = JSONObject(result).optString("access_token")
                    var uid = JSONObject(result).optString("uid")
                    var user : UserBean = UserBean()
                    user.access_token = token
                    user.uid = uid
                    view.loginSuccess(user)
                }else{
                    view.loginFailed(message)
                }
            }

            override fun onFailure(errorCode: Int, msg: String?) {
                super.onFailure(errorCode, msg)
                view.loginFailed(msg)


            }
        })
    }
}